<template>
  <div class="list"
    style="padding: 26px 46px;display: flex;flex-wrap: wrap;position: relative;margin-bottom: 36px;gap: 26px;cursor: pointer;">
    <el-button type="primary" icon="el-icon-edit" circle style="position: absolute;right: 260px;"
      @click="publish()"></el-button>
    <el-card class="box-card" v-for="item in lifesharings" style="width: 320px;box-sizing: border-box;"
      @click.native="toDetail(item.postId, item.postType, item.author)">
      <!-- 图片 -->
      <div class="img" style="height: 220px;text-align: center;">
        <img :src="item.postImg" alt="" style="width: 220px;height: 220px;">
      </div>
      <!-- 标题 -->
      <div class="title"
        style="text-align: center;font-family: '微软雅黑';color: #303133;font-weight: 574;margin-top: 12px;">

        <el-tooltip :content="item.title" placement="bottom" effect="light">
          <span class="item-title" style="text-align: center;"> {{ item.title }}</span>
        </el-tooltip>
      </div>
      <!-- 内容 -->
      <div class="contenttext"
     style="font-size: 14px; margin-top: 12px; height: 80px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 5; -webkit-box-orient: vertical; text-overflow: ellipsis; white-space: normal; line-height: 16px;text-indent: 2em;">
    {{ item.content }}
</div>

      <!-- 作者 -->
      <!-- 作者 -->
      <div class="user" style="margin-top: 12px;height: 64px;display: flex;align-items: center;color: #606266;">
        <!-- 作者头像 -->
        <img :src="item.postImg" alt="" width="42px" height="42px" style="border-radius: 46px;">

        <!-- 作者姓名（超过一定宽度时省略）-->
        <span
          style="margin-left: 12px; max-width: 136px; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;flex:30%;">
          {{ item.authorName }}
        </span>

        <!-- 发表时间（确保时间不换行）-->
        <span style="margin-left: 36px; max-width: 146px; font-size: 14px; white-space: nowrap;flex:30%">
          {{ item.postDate }}
        </span>
      </div>


    </el-card>
    <!-- 弹窗   -->
    <el-dialog title="生活分享":visible.sync="dialogVisible" width="30%" :close-on-click-modal="false" center>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item label="帖子名称" label-width="150px" prop="title">
          <el-input v-model="ruleForm.title" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="帖子内容" label-width="150px" prop="content">
          <el-input type="textarea" v-model="ruleForm.content" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="图片" label-width="150px">
          <el-upload action="http://localhost:9001/api/file/upload" multiple :on-success="handleSuccess" ref="upload">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分页容器 -->
    <div class="pagination-wrapper"
      style="width: 100%; display: flex; justify-content: center;position: absolute;left: -12%;bottom: -60px;">
      <el-pagination v-show="pageShow" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-size="pageSize" :page-sizes="[3, 6, 9, 12]"
        layout="total, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  </div>

</template>


<script>
// 导入api
import API from "@/api/request";

export default {
  data() {
    return {
      //帖子列表
      lifesharings: [],
      //数据总数
      total: 0,
      //当前页
      currentPage: 1,
      //每页数量
      pageSize: 3,
      // 控制分页显示
      pageShow: false,
      //帖子表单开关
      dialogVisible: false,
      ruleForm: {
      },
      rules: {
        title: [
          { required: true, message: '请填写帖子标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '帖子内容', trigger: 'blur' }
        ]
      },
      entity:{},
      imgurl:'',
      user:{}
    }
  },
  methods: {
    getlifeSharings() {
      API.get("/api/lifeSharing/pageList", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.total = res.data.data.total;
          this.currentPage = res.data.data.current;
          this.lifesharings = res.data.data.records;
          this.lifesharings.forEach(item => {
            item.postDate = this.formatDate(item.postDate);
          });
          console.log(this.lifesharings)
          console.log(res)
          //当评论数量为0时,不显示分页列表,显示空白页
          if (this.total > 0) {
            this.pageShow = true;
          }
        }
      })
    },
    //控制页数的函数
    handleSizeChange(val) {
      this.pageSize = val;
      console.log(`每页 ${val} 条`);
      this.getlifeSharings();
    },
    // 控制页码的函数
    handleCurrentChange(val) {
      this.currentPage = val;
      console.log("查看当前页" + this.currentPage);
      console.log(`当前 ${val} 页`);
      this.getlifeSharings();
    },
    //跳转详情页
    toDetail(id, type, stuId) {
      console.log("点击了")
      console.log(id, type, stuId)
      this.$router.push({ path: '/detail', query: { id: id, type: type, stuId: stuId } })
    },
    // 函数：去除时分秒，只保留日期部分
    formatDate(dateString) {
      const date = new Date(dateString); // 将字符串转换为 Date 对象
      return date.toISOString().split('T')[0]; // 获取 yyyy-mm-dd 部分
    },
    publish() {
      this.dialogVisible = true;
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          API.post('/api/lifeSharing/add',{
            "name":this.ruleForm.title,
            "content":this.ruleForm.content,
            "postImage":this.imgurl,
            "author":this.user.studentId
          }).then(res=>{
            if(res.data.code==200){
              this.$notify.success("发表成功!");
              this.dialogVisible=false;
              this.ruleForm={}
              this.reload();
            }else{
              this.$notify.error("发表失败!");
              this.ruleForm={}
              this.reload();
            }
          })
         
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleSuccess(res) {
      console.log(res)
      //修改图片路径
      this.imgurl = res.data;
      console.log("图片" + this.imgurl)
    },


  },
  created() {
    this.getlifeSharings();
    this.user = sessionStorage.getItem('user') ? JSON.parse(sessionStorage.getItem('user')) : {}
  
  }
};
</script>

<style scoped>
/* 控制分页容器的样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  /* 使用 flex 来居中对齐 */
  margin-top: 20px;
}

/* 分页控件 */
.el-pagination {
  display: block;
  /* 确保分页控件是块级元素 */
  margin: 0 auto;
  /* 水平居中 */
}
</style>